package com.sitanyun.merchant.guide.frament.view.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.RecTraListAdatper;
import com.sitanyun.merchant.guide.adapter.TrajeListAdapter;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.BaseEntity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.BehavioStaticsBean;
import com.sitanyun.merchant.guide.bean.CallPhonesBean;
import com.sitanyun.merchant.guide.bean.TrajeBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.PhoneUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuikit.tuicontact.bean.ContactItemBean;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 用户轨迹
 */

public class TrajeActivity extends BaseActivity {

    @BindView(R.id.tra_img)
    CircleImageView traImg;
    @BindView(R.id.tra_name)
    TextView traName;
    @BindView(R.id.tra_stars)
    ImageView traStars;
    @BindView(R.id.tra_starss)
    ImageView traStarss;
    @BindView(R.id.tra_starsss)
    ImageView traStarsss;
    @BindView(R.id.usertraje)
    LinearLayout usertraje;
    @BindView(R.id.interactive)
    LinearLayout interactive;
    @BindView(R.id.callphone)
    LinearLayout callphone;
    @BindView(R.id.tra_ll)
    TextView traLl;
    @BindView(R.id.tra_ly)
    TextView traLy;
    @BindView(R.id.tra_tp)
    TextView traTp;
    @BindView(R.id.tra_msg)
    LinearLayout traMsg;
    @BindView(R.id.ll_callphone)
    LinearLayout llCallphone;
    @BindView(R.id.callphones)
    ImageView callphones;
    @BindView(R.id.lv_tra)
    ListView lvTra;
    @BindView(R.id.rec_tra)
    RecyclerView recTra;
    @BindView(R.id.sw_untreated)
    SwipeRefreshLayout swUntreated;
    private BehavioStaticsBean behavioStaticsBean;
    private int type;
    private PopupWindow popupWindow;
    private TrajeListAdapter trajeListAdapter;
    private BaseEntity baseEntity;
    private RecTraListAdatper recTraListAdatper;
 //   private String datetime;
    private List<TrajeBean.DataBean> orderbeanlist;
    private String datetime="null";
    @Override
    public int getLayoutId() {
        return R.layout.activity_traje;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("用户轨迹");
    }

    @Override
    public void initView() {
        //创建布局管理
        orderbeanlist = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(TrajeActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recTra.setLayoutManager(layoutManager);
        recTraListAdatper = new RecTraListAdatper(TrajeActivity.this);
        recTra.setAdapter(recTraListAdatper);
        recTraListAdatper.notifyDataSetChanged();
        //头部信息
        initusers();
        //用户轨迹
        initdate(datetime);
        //刷新
        swUntreated.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //用户轨迹
                datetime="null";
                initdate(datetime);
                recTraListAdatper.notifyDataSetChanged();
            }
        });

        //加载更多
        recTraListAdatper.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                initdate(datetime);
            }
        });
    }

    private void initusers() {
        OkHttpUtils.get().url(Urls.getConsumerBehaviorStatics)
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .addHeader("Content-Type", "application/json")
                .addParams("consumerId", getIntent().getStringExtra("cid"))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                behavioStaticsBean = new Gson().fromJson(response, BehavioStaticsBean.class);
                if (behavioStaticsBean.getCode() == 0) {
                    if (behavioStaticsBean.getData().getPhone() == null) {
                        llCallphone.setBackground(getDrawable(R.drawable.tras_shap_radio));
                        Glide.with(TrajeActivity.this).load(R.mipmap.callphoneh).into(callphones);

                    }
                    Glide.with(TrajeActivity.this).load(behavioStaticsBean.getData().getHeadUrl()).error(R.mipmap.cimg).into(traImg);
                    if (behavioStaticsBean.getData().getCName()==null){
                        traName.setText("访客");
                    }else {
                        traName.setText(behavioStaticsBean.getData().getCName());
                    }
                    traLl.setText(behavioStaticsBean.getData().getBrowseNum() + "");
                    traLy.setText(behavioStaticsBean.getData().getMessageNum() + "");
                    traTp.setText(behavioStaticsBean.getData().getMeetingNum() + "");
                    switch (behavioStaticsBean.getData().getStars()) {
                        case 0:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStarss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStarsss);
                            break;
                        case 1:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStarss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStarsss);
                            break;
                        case 2:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStarss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(traStarsss);
                            break;
                        case 3:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStarss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(traStarsss);
                            break;
                    }
                } else {
                    ToastUtil.showToast(TrajeActivity.this, behavioStaticsBean.getMsg() + "");
                }
            }
        });
    }

    private void initdate(String s) {

        OkHttpUtils.get().url(Urls.consumerBehaviorHistory)
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .addHeader("Content-Type", "application/json")
                .addParams("date", s)
                .addParams("merchantNodeId", SharedPreferenceUtil.getStringData("nodeid"))
                .addParams("cId", getIntent().getStringExtra("cid"))
                .addParams("days", "3")
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {
                swUntreated.setRefreshing(false);
            }

            @Override
            public void onResponse(String response, int id) {
                swUntreated.setRefreshing(false);
                TrajeBean trajeBean = new Gson().fromJson(response, TrajeBean.class);
//                trajeListAdapter = new TrajeListAdapter(TrajeActivity.this, trajeBean.getData());
//                lvTra.setAdapter(trajeListAdapter);
                if (trajeBean.getCode() == 0) {
                    orderbeanlist.clear();
                    if (trajeBean.getData().size() == 0) {
                        recTraListAdatper.loadMoreEnd();
                        recTraListAdatper.notifyDataSetChanged();
                        return;
                    } else {
                        if (datetime.equals("null")){
                            datetime = trajeBean.getData().get(0).getDate();
                            recTraListAdatper.setNewData(trajeBean.getData());
                            orderbeanlist.addAll(trajeBean.getData());
                            recTraListAdatper.notifyDataSetChanged();
                        }else {
                            //orderbeanlist.addAll(orderBean.getData());
                            //底部没有数据时
                            if (trajeBean.getData().size()==0) {
                                recTraListAdatper.loadMoreEnd();
                            } else {
                                //滑动加载数据
                                List<TrajeBean.DataBean> data1 =trajeBean.getData();
                                orderbeanlist.addAll(data1);
                                datetime = data1.get(0).getDate();
                                recTraListAdatper.addData(data1);
                                recTraListAdatper.notifyDataSetChanged();
                                recTraListAdatper.loadMoreComplete();

                            }

                        }

                    }

                } else {
                    ToastUtil.showToast(TrajeActivity.this, "用户轨迹请求失败");
                }

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_callphone, R.id.tra_msg, R.id.tra_img, R.id.tra_name, R.id.tra_stars, R.id.tra_starss, R.id.tra_starsss})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //电话
            case R.id.ll_callphone:
                if (behavioStaticsBean.getData().getPhone() != null) {
                    // initpopuview();
                    PhoneUtils.callPhone(TrajeActivity.this, behavioStaticsBean.getData().getPhone());
                } else {
                    return;
                }

                break;
            //留言
            case R.id.tra_msg:
                Bundle bundle = new Bundle();
                bundle.putString(TUIConstants.TUIChat.CHAT_ID, "cid_" + behavioStaticsBean.getData().getCId());
                bundle.putString(TUIConstants.TUIChat.CHAT_NAME, behavioStaticsBean.getData().getCName());
                bundle.putInt(TUIConstants.TUIChat.CHAT_TYPE, ContactItemBean.TYPE_C2C);
                TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, bundle);
                break;
            case R.id.tra_img:
                break;
            case R.id.tra_name:
                break;
            case R.id.tra_stars:
                break;
            case R.id.tra_starss:
                break;
            case R.id.tra_starsss:
                break;
        }
    }

    // 弹窗consumerId
    private void initpopuview() {
        OkHttpUtils.get().url(Urls.getConsumerInfo)
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .addHeader("Content-Type", "application/json")
                .addParams("consumerId", getIntent().getStringExtra("cid"))
                .addParams("sceneId", getIntent().getStringExtra("scenid"))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                CallPhonesBean callPhonesBean = new Gson().fromJson(response, CallPhonesBean.class);
                if (callPhonesBean.getCode() == 0) {
//1、使用Dialog、设置style
                    final Dialog dialog = new Dialog(TrajeActivity.this, R.style.DialogTheme);
                    //2、设置布局
                    View view = View.inflate(TrajeActivity.this, R.layout.callphone_item, null);
                    dialog.setContentView(view);
                    ImageView headerimg = view.findViewById(R.id.popu_headerimg);
                    TextView headername = view.findViewById(R.id.popu_headername);
                    TextView headerphone = view.findViewById(R.id.popu_headerphone);
                    ImageView enter_img = view.findViewById(R.id.enter_img);
                    TextView enter_name = view.findViewById(R.id.enter_store);
                    enter_name.setText(callPhonesBean.getData().getSceneName());
                    TextView entershar = view.findViewById(R.id.enter_shar);
                    TextView enter_bw = view.findViewById(R.id.enter_bw);
                    enter_bw.setText("同屏讲解：" + callPhonesBean.getData().getMeetingNum() + "     留言：" + callPhonesBean.getData().getMessageNum());
                    String times = callPhonesBean.getData().getLastBehaviorTime();
                    int intTime = callPhonesBean.getData().getDuring();
                    int h = intTime / 3600;
                    int m = (intTime % 3600) / 60;
                    int s = (intTime % 3600) % 60;
                    if (h == 0) {
                        entershar.setText(times.substring(11, times.length()) + "浏览   共" + m + "时" + s + "秒");
                    } else {
                        entershar.setText(times.substring(11, times.length()) + "浏览   共" + m + "时" + s + "秒");
                    }
                    Glide.with(TrajeActivity.this).load(callPhonesBean.getData().getPicUrl()).into(enter_img);
                    ImageView stars = view.findViewById(R.id.popu_headerstars);
                    ImageView starss = view.findViewById(R.id.popu_headerstarss);
                    ImageView starsss = view.findViewById(R.id.popu_headerstarsss);
                    headername.setText(callPhonesBean.getData().getCName());
                    headerphone.setText(callPhonesBean.getData().getPhone());


                    switch (callPhonesBean.getData().getStars()) {
                        case 0:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(stars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(starss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(starsss);
                            break;
                        case 1:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(stars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(starss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(starsss);
                            break;
                        case 2:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(stars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(starss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xwei).into(starsss);
                            break;
                        case 3:
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(stars);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(starss);
                            Glide.with(TrajeActivity.this).load(R.mipmap.xxuan).into(starsss);
                            break;
                    }
                    Glide.with(TrajeActivity.this).load(callPhonesBean.getData().getHeadUrl()).into(headerimg);


                    Window window = dialog.getWindow();
                    //设置弹出位置
                    window.setGravity(Gravity.CENTER);
                    //设置弹出动画
                    //   window.setWindowAnimations(R.style.main_menu_animStyle);
                    //设置对话框大小
                    window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    dialog.show();

                    dialog.findViewById(R.id.callphones).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            PhoneUtils.callPhone(TrajeActivity.this, callPhonesBean.getData().getPhone());
                            dialog.dismiss();
                        }
                    });

                } else {
                    ToastUtil.showToast(TrajeActivity.this, callPhonesBean.getMsg() + "");
                    return;
                }
            }
        });


    }
}
